using CfgTable;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using NetProtocol.POD;
using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UIN_MailListPanel : UIBaseNode
    {

        #region Template Generate,don't modify
        protected partial class UIB_UIN_MailLIstPanel
        {
            #region ObjectBinding Generate
            public GameObject tips { protected set; get; }
            public UnityEngine.UI.ExLoopVerticalScrollRect loopVerticalScrollRect { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btnDel { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btnGet { protected set; get; }
            public GameObject emptyTips { protected set; get; }
            public GameObject butList { protected set; get; }
            public IQIGame.Onigao.Framework.ExText totalNum { protected set; get; }
            public IQIGame.Onigao.Framework.ExText unreadNum { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<UnityEngine.GameObject>("tips", out var __tbv0);
                this.tips = __tbv0;
                __binding.TryGetVariableValue<UnityEngine.UI.ExLoopVerticalScrollRect>("loopVerticalScrollRect", out var __tbv1);
                this.loopVerticalScrollRect = __tbv1;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnDel", out var __tbv2);
                this.btnDel = __tbv2;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnGet", out var __tbv3);
                this.btnGet = __tbv3;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("emptyTips", out var __tbv4);
                this.emptyTips = __tbv4;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("butList", out var __tbv5);
                this.butList = __tbv5;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("totalNum", out var __tbv6);
                this.totalNum = __tbv6;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("unreadNum", out var __tbv7);
                this.unreadNum = __tbv7;
            }
            #endregion ObjectBinding Generate 
        }
        #endregion Template Generate,don't modify


        UIB_UIN_MailLIstPanel ui { get; set; }

        protected override void BeforeInit()
        {
            ui = new UIB_UIN_MailLIstPanel();
            ui.InitBinding(this.csObjBind);
        }
        LoopScrollAdapter<UIN_MailCell> loopCells = null;

        private List<MailSimplePOD> mailDataList;
        private int startIndex = 0;
        protected override void OnInit()
        {
            this.loopCells = this.InitLoopScroll<UIN_MailCell>(this.ui.loopVerticalScrollRect, this.OnMailCellChanged);
            this.loopCells.InitUnitSelected(UnitSelectType.ByExButton, this.OnMailCellSelected);
            this.ui.btnDel.onClick.AddListener(this.OnBtnDelClicked);
            this.ui.btnGet.onClick.AddListener(this.OnBtnGetClicked);
        }

        protected override void OnShow()
        {

        }

        protected override void OnHide()
        {

        }

        protected override void OnDispose()
        {
            this.loopCells = null;
            this.mailDataList?.Clear();
            this.mailDataList = null;
            this.startIndex = 0;
        }
        /// <summary>
        /// 首次打开界面需要向服务器请求邮件列表数据
        /// </summary>
        /// <param name="bIsFirstIn">是否是首次进入</param>
        public void Show(bool bIsFirstIn)
        {
            this.SendMailGet(bIsFirstIn).Forget();
        }
        void RefreshPanel()
        {
            this.startIndex = Mathf.Min(this.mailDataList.Count, this.startIndex);
            this.loopCells.RefillCells(this.mailDataList.Count, this.startIndex);
            if (this.mailDataList.Count == 0)
            {
                this.ui.emptyTips.SetActive(true);
                this.ui.butList.SetActive(false);
                this.ui.tips.SetActive(false);
            }
            else
            {
                this.ui.emptyTips.SetActive(false);
                this.ui.butList.SetActive(true);
                this.ui.tips.SetActive(true);
                this.ui.totalNum.text = $"{this.mailDataList.Count}/{APIUIConst.MailMaxCountLimit}";
                this.ui.unreadNum.text = this.CaculateUnreadNum().ToString();
            }
        }
        async UniTaskVoid SendMailGet(bool bIsSendMailGet)
        {
            if (bIsSendMailGet)
            {
                var result = await MailModule.NetCore.CS_getMails((int)MailType.Normal);
                if (result.IsFail)
                {
                    return;
                }
                this.mailDataList = result.mailList;
                this.mailDataList.Sort((mail1, mail2) =>
                {
                    int nValue = mail2.canGetItem.CompareTo(mail1.canGetItem);
                    if (nValue == 0)
                        nValue = mail2.createTime.CompareTo(mail1.createTime);
                    return nValue;
                });
            }

            this.Show();
            this.RefreshPanel();
        }

        int CaculateUnreadNum()
        {
            int nTempNum = 0;
            for (int i = 0; i < this.mailDataList.Count; i++)
            {
                if (!this.mailDataList[i].isRead)
                {
                    nTempNum++;
                }
            }
            return nTempNum;
        }
        async UniTaskVoid SendMailDelete()
        {
            if (this.mailDataList.Count == 0) return;
            List<long> list = ListPool<long>.Get();
            foreach (var tempMailData in this.mailDataList)
            {
                if (!tempMailData.isRead)
                {
                    continue;
                }
                if (tempMailData.canGetItem)
                {
                    continue;
                }
                list.Add(tempMailData.id);

            }
            if (list.Count == 0)
            {
                ListPool<long>.Put(list);
                NoticeModule.ShowNoticeNoCall(20001);
                return;
            }
            var result = await MailModule.NetCore.CS_deleteMail(list);
            ListPool<long>.Put(list);
            if (result.IsFail)
            {
                return;
            }
            foreach (var deletedItem in result.deletedList)
            {
                this.DeleteOne(deletedItem);
            }
            this.RefreshPanel();
        }

        async UniTaskVoid SendMailPickUp()
        {
            if (this.mailDataList.Count == 0) return;
            List<long> list = ListPool<long>.Get();
            foreach (var tempMailData in this.mailDataList)
            {
                if (!tempMailData.canGetItem)
                {
                    continue;
                }
                list.Add(tempMailData.id);
            }
            if (list.Count == 0)
            {
                ListPool<long>.Put(list);
                NoticeModule.ShowNoticeNoCall(20002);
                return;
            }
            var result = await MailModule.NetCore.CS_pickUp(list);
            ListPool<long>.Put(list);
            if (result.IsFail)
            {
                return;
            }
            foreach (var item in result.pickedList)
            {
                foreach (var mailData in this.mailDataList)
                {
                    if (mailData.id == item)
                    {
                        mailData.isRead = true;
                        mailData.canGetItem = false;
                        break;
                    }
                }
            }
            NoticeModule.ShowUIItemGet(result.getItems);
            this.RefreshPanel();
        }

        void OnBtnDelClicked()
        {
            this.SendMailDelete().Forget();
        }

        void OnBtnGetClicked()
        {
            this.SendMailPickUp().Forget();
        }

        void OnMailCellChanged(UIN_MailCell item, int index)
        {
            item.Show(this.mailDataList[index]);
        }
        void OnMailCellSelected(int index, UIN_MailCell item)
        {
            this.startIndex = index;
            this.ViewMailDetail(item.mailSimplePOD);

        }
        void ViewMailDetail(MailSimplePOD mailData)
        {
            var belongWindow = this.belongWindow as UIMail;
            belongWindow.MailListPanel.Hide();
            belongWindow.MailDetailPanel.Show(mailData);
        }

        public void DeleteOne(long nMailUid)
        {
            foreach (var mailData in this.mailDataList)
            {
                if (mailData.id == nMailUid)
                {
                    this.mailDataList.Remove(mailData);
                    break;
                }
            }
        }

    }
}
